﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Anderson.NetLobby.Common
{
    public class ObjectSerialize
    {

        /// <summary>
        /// 将对象序列化为字节数组
        /// </summary>
        public static byte[] Serialize(object target)
        {
            byte[] result = null;

            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bw = new BinaryFormatter();
                bw.Serialize(ms, target);

                result = new byte[ms.Length];
                Buffer.BlockCopy(ms.GetBuffer(), 0, result, 0, (int)ms.Length);
            }

            return result;
        }

        /// <summary>
        /// 将字节数组反序列化为对象
        /// </summary>
        public static object Deserialize(byte[] bytes)
        {
            object target = null;

            using (MemoryStream ms = new MemoryStream(bytes))
            {
                BinaryFormatter bw = new BinaryFormatter();

                target = bw.Deserialize(ms);
            }
                
            return target;
        }
    }
}
